package com.campus.backend.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.backend.bean.user.UserQueryParam;
import com.campus.backend.bean.user.UserStatusBean;
import com.campus.backend.entity.User;
import com.campus.backend.mapper.UserMapper;
import com.campus.backend.vo.user.UserVo;
import com.campus.common.bean.common.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-05-21
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    /**
     * 查询用户列表（分页）
     * @param param 查询参数
     * @return 分页结果
     */
    public PageInfo<UserVo> getUserDataPage(UserQueryParam param) {
        PageInfo<User> pageInfo = PageHelper.startPage(param.getPageNo(), param.getPageSize())
                .doSelectPageInfo(() -> this.getUserDataList(param));

        // 转换为VO
        List<UserVo> voList = pageInfo.getList().stream()
                .map(user -> {
                    UserVo vo = new UserVo();
                    BeanUtil.copyProperties(user, vo);
                    return vo;
                }).collect(Collectors.toList());

        return PageUtil.convertPageInfo(pageInfo, voList);
    }

    private List<User> getUserDataList(UserQueryParam param) {
        return this.list(new LambdaQueryWrapper<User>()
                .like(StringUtils.isNotBlank(param.getNickname()), User::getNickname, param.getNickname())
                .like(StringUtils.isNotBlank(param.getPhone()), User::getPhone, param.getPhone()));
    }

    /**
     * 批量更新用户状态
     * @param userStatusBean 用户启用/禁用参数
     * @return 更新结果
     */
    public boolean batchUpateStatus(UserStatusBean userStatusBean) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(User::getId, userStatusBean.getIds())
                     .set(User::getStatus, userStatusBean.getStatus());
        return update(updateWrapper);
    }

}